package val.to.uploader;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import val.to.BitmapUtil;
import val.to.Globals;
import val.to.Utility;
import val.to.ValtoServices;
import val.to.entities.PhotoPost;
import val.to.entities.UploadItem;
import val.to.entities.UploadItem.UploadStatus;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class PhotoUploadService extends IntentService {
	public PhotoUploadService() {
		super("PhotoUploadService");
	}

	UploadItem mItem;

	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			Log.d("Service", "Handle");
			int itemID = (int) intent.getIntExtra("itemid", -1);

			mItem = Globals.UploadManager.UploadStarted(itemID);
			if (mItem == null)
				return;

			// check credits
			int waitTime;
			if ((waitTime = GetWaitTime()) > 0) {
				mItem.setErrorMessage("You reached the 50 uploads per hour limit");
				mItem.setErrorDetails("Upload will be available again in "
						+ Utility.getRoughStringForTimeDiff(waitTime * 1000));
				mItem.SetStatus(UploadStatus.Error);
				Globals.UploadManager.OnStatusChanged(mItem);
				Log.d("Service", "Handle Finished");
				return;
			}

			JSONObject response = null;

			response = UploadPhoto();
			if (response == null) {
				mItem.SetStatus(UploadStatus.Error);
				return;
			}
			PhotoPost post = ParseImgurResponse(response, mItem.IsFacebook());
			if (post == null) {
				mItem.SetStatus(UploadStatus.Error);
				return;
			}
			boolean res = ValtoServices.postPhoto(post);
			if (!res) {
				mItem.SetStatus(UploadStatus.Error);
				return;
			} else if (mItem.IsFacebook()) {
				UploadToFaceBook(post.getPhotoUri());
			}
			mItem.SetStatus(UploadStatus.Uploaded);
			Globals.UploadManager.OnStatusChanged(mItem);
			Log.d("Service", "Handle Finished");
		} catch (Exception e) {
		}

	}

	// if imgur credits == 0 returns the waiting time in seconds ow 0
	private int GetWaitTime() {
		try {
			HttpGet creditsRequest = new HttpGet(
					"http://api.imgur.com/2/credits.json");
			HttpClient client = new DefaultHttpClient();
			JSONObject j = null;
			try {
				HttpResponse res = client.execute(creditsRequest);
				String resString = EntityUtils.toString(res.getEntity());
				j = new JSONObject(resString);
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			} catch (JSONException e) {
			}

			if (j != null) {

				j = (JSONObject) j.get("credits");

				int credits = j.getInt("remaining");
				if (credits < 10)
					return j.getInt("refresh_in_secs");

			}

		} catch (Exception e) {
		}

		return 0;
	}

	private PhotoPost ParseImgurResponse(JSONObject Response, boolean sharedOnFB) {
		try {
			if (Response.has("upload")) {
				JSONObject links = Response.getJSONObject("upload")
						.getJSONObject("links");
				String org = links.getString("original");
				String thumb = links.getString("small_square");
				String largeThumb = links.getString("large_thumbnail");
				return new PhotoPost(org, largeThumb, thumb,
						mItem.getCaption(), sharedOnFB);
			} else if (Response.has("error")) {
				mItem.setErrorMessage("Images server returned an error");
				mItem.setErrorDetails(Response.getJSONObject("error")
						.getString("message"));
			}
		} catch (Exception e) {
		}

		return null;
	}

	// Uploads an image to Imgur
	private JSONObject UploadPhoto() {
		byte[] image = null;
		try {
			image = BitmapUtil.scaleImage(getContentResolver(),
					mItem.getImageUri());
		} catch (FileNotFoundException e) {
			mItem.setErrorMessage("Photo can't be found");
			return null;
		}

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://api.imgur.com/2/upload.json");

		MultipartEntity entity = new MultipartEntity();

		try {
			entity.addPart("type", new StringBody("file"));
			entity.addPart("key", new StringBody(
					getString(val.to.R.string.imgur_key)));
			entity.addPart("image", new ByteArrayBody(image, "Valto"));
		} catch (UnsupportedEncodingException e) {
			return null;
		}
		httppost.setEntity(entity);
		HttpResponse response;
		try {
			response = httpclient.execute(httppost);
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			mItem.setErrorMessage("Connection Error");
			return null;
		}
		String res;
		try {
			res = EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			return null;
		}
		try {
			return new JSONObject(res);
		} catch (JSONException e) {
			return null;
		}
	}

	private void UploadToFaceBook(String ImageUrl) {
		Bundle reqParam = new Bundle();
		reqParam.putString("url", ImageUrl);
		try {
			Globals.FacebookSession.request("me/photos", reqParam, "POST");
		} catch (IOException e) {
		}
	}
}
